const path = require("path");
const compression = require("compression");
const logger = require("morgan");
const bodyParser = require("body-parser");
const methodOverride = require("method-override");
const helmet = require("helmet");
const cors = require("cors");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const hjs = require("hjs");
const express = require("express");
const app = express();
const store = require("./src/store/index");
const { client, get, set, has, del } = require("./src/store/redis");
const { Get, Post, Put, Delete, fetchImage } = require("./src/utils/index");
const MysqlPool = require("./src/store/mysql");
const serverConfig = require("./src/utils/config");

app.$redis = { client, get, set, has, del };
app.$store = store;
app.$request = {
  Get,
  Post,
  Put,
  Delete,
  fetchImage,
};
app.$pool = new MysqlPool({ ...serverConfig.mySql }).getPool();

//app.set("env", "development");
app.set("view engine", "hjs");
app.use(
  compression({
    filter: function (req, res) {
      return /json|text|javascript|css|ttf|woff|eot|svg/.test(
        res.getHeader("Content-Type")
      );
    },
    level: 9,
  })
);
app.use(logger());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false })); //extended为false表示使用querystring来解析数据，这是URL-encoded解析器
// parse application/json
app.use(bodyParser.json());
app.use(methodOverride());
app.use(
  helmet({
    noCache: true,
  })
);
app.use(cors());
app.use(cookieParser());
app.use(
  session({
    resave: false,
    saveUninitialized: true,
    secret: (Math.random(1000) + "").replace(/\./gim, ""),
    cookie: {
      maxAge: 60 * 1000 * 30,
    }, // 过期时间（毫秒）
  })
);
app.set("hostname", serverConfig.ip);
app.set("port", serverConfig.port);
app.set("views", __dirname + serverConfig.path.template);
app.use("/", express.static(path.join(__dirname, serverConfig.path.static)));
app.use("/public", express.static(__dirname + serverConfig.path.icon));
app.use(function (err, req, res, next) {
  console.log("ERROR: ", err);
  res.status(404);
  res.render("404", {});
});
//app.use(app.router);
app.enable("trust proxy");

const { routes } = require("./src/router/index");
routes(app);

module.exports = { app, serverConfig };
